package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.RelativeDateFormat;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.Movements;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.PicUploadResult;
import com.tanhua.server.vo.VideoVo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class VideoService {

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Reference(version = "1.0.0")
    private VideoApi videoApi;
    public String saveVideo(MultipartFile picFile, MultipartFile videoFile) {
        User user = UserThreadLocal.get();
        Video video = new Video();
        video.setUserId(user.getId());
        video.setSeeType(1);
        try {
            //上传封面图片
            PicUploadResult picUploadResult = picUploadService.upload(picFile);
            video.setPicUrl(picUploadResult.getName());

            //上传小视频
            StorePath storePath = storageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize()
                    , StringUtils.substringAfter(videoFile.getOriginalFilename(), "."),
                    null);
            //保存小视频访问路径
            video.setVideoUrl(fdfsWebServer.getWebServerUrl() + "/" + storePath.getFullPath());
            String videoId = videoApi.saveVideo(video);
            return videoId;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    //查询小视频列表
    public PageResult queryVideoList(Integer page, Integer pageSize) {
        Long userId = UserThreadLocal.get().getId();
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setPages(0);
        pageResult.setCounts(0);
        List<Video> videoList = videoApi.queryVideoList(page, pageSize);
        //集合为空,直接返回
        if (CollectionUtils.isEmpty(videoList))
            return pageResult;
        //获取发布小视频的用户id集合
        Set<Long> userIds = videoList.stream().map(Video::getUserId).collect(Collectors.toSet());
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(UserInfo::getUserId, userIds);
        //获取发布动态的好友信息
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(wrapper);
        //封装数据VideoVoList
        List<VideoVo> videoVoList = new ArrayList<>();
        for (Video video : videoList) {
            for (UserInfo userInfo : userInfoList) {
                if (video.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    VideoVo videoVo = new VideoVo();
                    videoVo.setId(video.getId().toHexString());
                    videoVo.setAvatar(userInfo.getLogo());
                    videoVo.setUserId(userInfo.getUserId());
                    videoVo.setNickname(userInfo.getNickName());
                    videoVo.setCover(video.getPicUrl());
                    videoVo.setVideoUrl(video.getVideoUrl());
                    videoVo.setSignature("就让天再遮不住我眼~");//签名
                    //TODO 评论数
                    String CommentKey = "QUANZI_COMMENT_CONTENT_" + videoVo.getId();
                    Integer commentCount = null;
                    if (redisTemplate.hasKey(CommentKey)) {
                        commentCount = Integer.valueOf(redisTemplate.opsForValue().get(CommentKey));
                    } else {
                        commentCount = 0;
                    }
                    videoVo.setCommentCount(commentCount);
                    //是否关注
                    String followUserKey = "VIDEO_FOLLOW_USER_" + userId;
                    videoVo.setHasFocus(this.redisTemplate.hasKey(followUserKey) ? 1 : 0); //是否关注
                    // TODO 是否点赞（1是，0否）
                    String likeUserCommentKey = "QUANZI_COMMENT_LIKE_" + userId + "_" + video.getId();
                    videoVo.setHasLiked(redisTemplate.hasKey(likeUserCommentKey)? 1 : 0);
                    String likeCommentKey = "QUANZI_COMMENT_LIKE_" + video.getId();
                    //判断缓存中是否存有点赞数
                    Integer likeCount = null;
                    if (redisTemplate.hasKey(likeCommentKey)) {
                        likeCount = Integer.valueOf(redisTemplate.opsForValue().get(likeCommentKey));
                    } else {
                        likeCount = 0;
                    }
                    videoVo.setLikeCount(likeCount); //TODO 点赞数
                    videoVoList.add(videoVo);
                    break;
                }
            }
        }
        pageResult.setItems(videoVoList);
        return pageResult;
    }

    public Boolean followUser(Long followUserId) {
        User user = UserThreadLocal.get();
        videoApi.followUser(user.getId(),followUserId);
        //缓存中记录是否关注
        String followUserKey = "VIDEO_FOLLOW_USER_" + user.getId() + "_" + followUserId;
        redisTemplate.opsForValue().set(followUserKey,"1");
        return true;
    }

    public Boolean disFollowUser(Long followUserId) {
        User user = UserThreadLocal.get();
        videoApi.disFollowUser(user.getId(),followUserId);
        String followUserKey = "VIDEO_FOLLOW_USER_" + user.getId() + "_" + followUserId;
        redisTemplate.delete(followUserKey);
        return true;
    }
}
